<?php
/**
 *
 *  少女前线的某辅(wai)助(gua)授权用的验证类
 *
 *  by Akkariin 开源协议：MIT
 *
 */
class GirlsFrontline {
	
	/**
	 *
	 *  Hex2String 十六进制转字符串
	 *
	 */
	public static function Hex2String($hex)
	{
		$string = '';
		for($i = 0;$i < strlen($hex) - 1;$i += 2) {
			$string .= chr(hexdec($hex[$i] . $hex[$i+1]));
		}
		return $string;
	}

	/**
	 *
	 *  String2Hex 字符串转十六进制
	 *
	 */
	public static function String2Hex($string)
	{
		$hex = '';
		for($i = 0;$i < strlen($string);++$i) {
			$hex .= ((($c = dechex(ord($string{$i}))) && strlen($c) & 2) ? $c : "0{$c}");
		}
		return $hex;
	}

	/**
	 *
	 *  DataSwitch 对数据进行位与
	 *
	 */
	public static function DataSwitch($data, $key)
	{
		$rs = "";
		for($i = 0;$i < strlen($data);++$i) {
			$rs[$i] = ($data[$i] ^ $key[$i % strlen($key)]);
		}
		return $rs;
	}

	/**
	 *
	 *  AesEncrypt 进行 AES 加密
	 *
	 */
	public static function AesEncrypt($data, $key)
	{
		return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_PKCS1_PADDING);
	}
	
	/**
	 *
	 *  AesDecrypt 进行 AES 解密
	 *
	 */
	public static function AesDecrypt($data, $key)
	{
		return openssl_decrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
	}
	
	/**
	 *
	 *  ValidArgs 验证请求参数是否合法
	 *
	 */
	public static function ValidArgs($args)
	{
		return (
			isset($args['a'], $args['aaa']) &&
			!empty($args['a']) &&
			!empty($args['a']) &&
			is_string($args['a']) &&
			is_string($args['aaa'])
		);
	}
	
	/**
	 *
	 *  ValidKey 验证激活码是否合法
	 *
	 */
	public static function ValidKey($data, $key)
	{
		if(!preg_match("/^[A-Fa-f0-9]{32}$/", $data)) {
			return false;
		}
		$data = GirlsFrontline::Hex2String($data);
		$data = GirlsFrontline::AesDecrypt($data, GirlsFrontline::Hex2String($key));
		$exps = explode("#", $data);
		return (is_array($exps) && count($exps) == 4);
	}
	
	/**
	 *
	 *  GetFormatMsg 取得格式化后的消息内容
	 *
	 */
	public static function GetFormatMsg($msg, $status = 0, $key)
	{
		$encData = GirlsFrontline::DataSwitch(json_encode([
			"statusCode" => $status,
			"message"    => $msg
		], JSON_UNESCAPED_UNICODE), $key);
		return GirlsFrontline::String2Hex($encData);
	}
}
